package cn.shujuhai.workflow.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.shujuhai.common.aop.SysLogAspect;
import cn.shujuhai.common.pluging.data.ResultVo;
import cn.shujuhai.workflow.domain.Form;
import cn.shujuhai.workflow.domain.FormData;
import cn.shujuhai.workflow.domain.FormProcess;
import cn.shujuhai.workflow.mapper.FormProcessMapper;
import cn.shujuhai.workflow.service.FormDataService;
import cn.shujuhai.workflow.service.FormProcessService;
import cn.shujuhai.workflow.service.FormService;
import cn.shujuhai.workflow.service.flow.FlowableService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

/**
 * @author zdz18
 * @description 针对表【form_process】的数据库操作Service实现
 * @createDate 2025-03-25 11:30:21
 */
@Service
@RequiredArgsConstructor
public class FormProcessServiceImpl extends ServiceImpl<FormProcessMapper, FormProcess>
        implements FormProcessService {

    private final FormService formService;
    private final FormDataService formDataService;
    private static final Logger logger = LoggerFactory.getLogger(SysLogAspect.class);
    private final FlowableService flowableService;


    @Override
    public ResultVo<?> setProcessForm(FormProcess formProcess) {
        boolean save = this.save(formProcess);
        if (save) {
            return ResultVo.success();
        }
        return ResultVo.failure("表单选择失败！");
    }

    @Override
    public ResultVo<?> getFromField(String processDefinitionId) {
        var wrapper = new MPJLambdaWrapper<Form>();
        wrapper.selectAll(Form.class)
                .leftJoin(FormProcess.class, FormProcess::getFormId, Form::getFormId)
                .eq(FormProcess::getProcessDefinitionId, processDefinitionId);
        Form form = this.formService.list(wrapper).stream().findFirst().orElse(null);
        return ResultVo.success(form);
    }

    @Override
    public ResultVo<?> addFormData(FormData formData) {
        try {
            if (!StpUtil.isLogin()) {
                return ResultVo.failure("登录信息获取失败");
            }
        } catch (Exception e) {
            logger.warn(e.getMessage());
            return ResultVo.failure("登录信息获取失败");
        }
        Long submitUserId = StpUtil.getLoginIdAsLong();
        try {
            String processInstanceId = flowableService.startProcess(formData.getProcessDefinitionId());
            formData.setProcessInstanceId(processInstanceId);
            formData.setSubmitUserId(submitUserId);
            boolean save = this.formDataService.save(formData);
            if (save) {
                return ResultVo.success();
            }
            return ResultVo.failure("表单数据提交失败");
        } catch (Exception e) {
            return ResultVo.failure(e.getMessage());
        }
    }
}




